var express = require('express');
var router = express.Router();

var fs = require("fs");
var md5 = require("md5");
var conn = require('../conn');

/* GET adminusers listing. */

router.get('/login', function(req, res, next) {
	res.render('AdminLogin' );
});
router.post('/dologin', function(req, res, next) {
	req.body.password = md5(req.body.password);
	var sql = 'select * from adminusers where name="'+req.body.user+'" and password="'+req.body.password+'"';
	conn.query(sql,function(err,rows,fields){
		if (rows.length==0) {
			res.send('用户名或密码错误' );
		}else{
			req.session.if_login = true;
			req.session.username = rows[0].name;
			res.send('ok');
		}
	});
});

router.get('/register', function(req, res, next) {
	res.render('AdminRegister');
});
router.post('/register', function(req, res, next) {
	if (req.body.user=='') {
		res.send("用户名不能为空");
	}else if (req.body.password==''){
		res.send("密码不能为空");
	}else{
		var user = 'select * from adminusers where name="'+req.body.user+'"';
		conn.query(user,function(err,rows,fields){
			if (rows.length==0) {
				req.body.password = md5(req.body.password);
				var sql = 'insert into adminusers value(null,"'+req.body.user+'" ,"'+req.body.password+'")';
				conn.query(sql,function(err,rows,fields){
					res.send('注册成功' );
				});
			}else{
				res.send('用户已经被注册' );
			}
		});
	}
});
module.exports = router;
